<?php

namespace app\index\service;

use app\admin\dao\MemberInviteDao;
use app\admin\service\PersonnelService;
use app\common\model\Member;
use app\index\dao\AccountDao;
use app\index\dao\MemberDao;
use app\index\model\UM as UM;
use ShidianUtil\Utils\CheckUtil;
use ShidianUtil\Utils\RandUtil;
use think\Collection;
use think\exception\ValidateException;
use think\facade\Config;

/**
 * 用户
 * Class MemberService
 * @package app\session\service
 */
class MemberService
{

    private MemberDao $memberDao;

    private AccountDao $accountDao;
    private MemberInviteDao $memberInviteDao;

    public function __construct(MemberDao $memberDao, AccountDao $accountDao, MemberInviteDao $memberInviteDao)
    {
        $this->memberDao = $memberDao;
        $this->accountDao = $accountDao;
        $this->memberInviteDao = $memberInviteDao;
    }

    /**
     * 新增用户
     * @param array $params
     * @return Member
     */
    public function add(array $params): Member
    {
        $params['channel'] ??= '0';
        $params['pf'] ??= '';
        $params['chain'] ??= '';
        $params['promotionGroupId'] ??= '0';
        $params['inviteCode'] ??= null;
        $params['wanzhengNicheng'] = 1;
        $params['wanzhengTouxiang'] = 1;
        $params['openidWechat'] ??= '';
        $params['followedWechat'] = not_blank($params['openidWechat']) ? '1' : '0';

        // 用户昵称
        if (is_blank($params['nickname'] ?? null)) {
            $params['nickname'] = ('1' . mt_rand(1000, 9999)) . '_' . RandUtil::letters(5, true);
            $params['wanzhengNicheng'] = '0';
        }

        // 头像
        if (is_blank($params['headImgUrl'] ?? null)) {
            $params['headImgUrl'] = '/defaultavatar/' . mt_rand(1, 22) . ".jpg";
            $params['wanzhengTouxiang'] = '0';
        }

        $time = time();
        $member = [
            'sid' => '',
            'status' => 1,
            'checkStatus' => 1,
            'type' => 0,
            'phone' => $params['phone'] ?? '',
            'passwd' => $params['passwd'] ?? '',
            'salt' => RandUtil::numberAndLetters(6, false),
            'unionid' => $params['unionid'] ?? '',
            'openidWeiXin' => $params['openidWeiXin'] ?? '',
            'openidWechat' => $params['openidWechat'] ?? '',
            'openidWechatOpen' => $params['openidWechatOpen'] ?? '',
            'unionidBaidu' => $params['unionidBaidu'] ?? '',
            'openidBaidu' => $params['openidBaidu'] ?? '',
            'unionidDouyin' => $params['unionidDouyin'] ?? '',
            'openidDouyin' => $params['openidDouyin'] ?? '',
            'nickname' => $params['nickname'] ?? '',
            'headImgUrl' => $params['headImgUrl'] ?? '',
            // 'cropImgUrl' => $params['cropImgUrl'] ?? '',
            'wanzhengNicheng' => $params['wanzhengNicheng'],
            'wanzhengTouxiang' => $params['wanzhengTouxiang'],
            'followedWechat' => $params['followedWechat'] ?? '0',
            'origin' => $params['origin'] ?? '',
            'channel' => $params['channel'],
            'pf' => $params['pf'],
            'chain' => $params['chain'],
            'promotionGroupId' => $params['promotionGroupId'],
            'userPersonnelId' => '0',
            'updated' => $time,
            'created' => $time
        ];

        // 写入用户模型
        $record = $this->memberDao->insertActive($member);

        // 写入资金账户 & 获客卡 & 通信币 && 保证金
        $record->account()->save([]);
        $record->card()->save([]);
        $record->coin()->save([]);
        $record->margin()->save([]);

        // 绑定邀请人
        if (not_blank($params['inviteCode'])) {

            $inviterId = Member::where('inviteCode', $params['inviteCode'])->value('id');
            if (is_id($inviterId)) {
                $this->memberInviteDao->insert($inviterId, $record->id, 2);

                // 邀请成功事件
                event('MemberInvited', ['memberIdInvite' => $record->id]);
            }
        }

        // 绑定员工
        $this->getPersonnelService()->bindPersonnel($record);

        return $record;
    }

    /**
     * 修改用户信息
     * @param int $id
     * @param array $params
     * @return Member|null
     */
    public function modify(int $id, array $params): ?Member
    {

        $allow = [
            'nickname', 'headImgUrl', 'phone',
        ];

        $allow = array_merge($allow, Member::UNIONID_ARR);

        $record = Member::where('id', $id)
            ->whereIn('status', [0, 1])
            ->find();

        if ($record) {
            $this->memberDao->updateActive($record, $params, $allow);
        }

        return $record;
    }

    /**
     * 设置账号状态
     * @param Member $member
     * @return void
     */
    public function memberStatusChange(Member $member, $status): void
    {
        $member->status = $status;
        $member->save();

        // 不是正常就退出登录
        if ($status != 1) {
            $this->getMemberTokenService()->delete($member->id);
        }
    }

    /**
     * 列表
     * @param \app\index\model\UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(?UM $user, ?int $page = null, ?int $page_size = null): Collection
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->memberDao->selectAll($page, $page_size, true);
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return Member
     */
    public function read(?UM $user, int $id): ?Member
    {
        $record = $this->memberDao->findByLogin($id);

        $record->customerServicePhone = Config::get('site.customer_service_phone');

        return $record;
    }

    /**
     * 用户修改自己的信息
     * @param UM $user
     * @param int $id
     * @param array $params
     */
    public function modifyByMember(UM $user, int $id, array $params): void
    {
        $record = Member::where('id', $id)->find();

        if (isset($params['nickname']) && not_blank($params['nickname'])) {
            $record->nickname = $params['nickname'];
            $record->wanzhengNicheng = 1;
        }

        if (isset($params['headImgUrl']) && not_blank($params['headImgUrl'])) {
            $record->headImgUrl = $params['headImgUrl'];
            $record->wanzhengTouxiang = 1;
        }

        if (isset($params['cropImgUrl']) && not_blank($params['cropImgUrl'])) {
            $record->cropImgUrl = $params['cropImgUrl'];
            $record->wanzhengTouxiang = 1;
        }

        if (isset($params['axbPhone'])) {
            if (!CheckUtil::isPhoneNumber($params['axbPhone'])) {
                throw new ValidateException('请输入正确的手机号');
            }
            $record->axbPhone = $params['axbPhone'];
        }

        $record->save();
    }

    private function getPersonnelService(): PersonnelService
    {
        return app(PersonnelService::class);
    }

    private function getMemberTokenService(): MemberTokenService
    {
        return app(MemberTokenService::class);
    }
}
